﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Input;
using AVICFEEDSApp.BingMapsGeocodeService;
using AVICFEEDSApp.Properties;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;
using System.Windows.Controls;

namespace AVICFEEDSApp
{
	public partial class AddressSearch : PhoneApplicationPage
	{
		private GeocodeServiceClient _geocodeServiceClient = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService");
		private SaveContactTask _saveContactTask = new SaveContactTask();

		public AddressSearch()
		{
			InitializeComponent();

			this.Loaded += new RoutedEventHandler(AddressSearch_Loaded);

			this._geocodeServiceClient.GeocodeCompleted += new EventHandler<GeocodeCompletedEventArgs>(GeocodeServiceClient_GeocodeCompleted);
			this._saveContactTask.Completed += new EventHandler<SaveContactResult>(SaveContactTask_Completed);
		}

		

		protected void AddressSearch_Loaded(object sender, RoutedEventArgs e)
		{
			SearchBox.Focus();
		}

		protected void GeocodeServiceClient_GeocodeCompleted(object sender, GeocodeCompletedEventArgs e)
		{
			// Clear the progress indicator
			SystemTray.SetProgressIndicator(this, new ProgressIndicator()
			{
				IsVisible = false
			});

			// Show an error message if something went wrong
			if (e.Error != null)
			{
				MessageBox.Show(e.Error.Message, "Search error", MessageBoxButton.OK);
			}
			else if (e.Result == null || e.Result.Results == null || e.Result.Results.Count == 0)
			{
				MessageBox.Show("We couldn't find any matches for the address you entered.", "No results", MessageBoxButton.OK);
			}
			else
			{
				SearchResultsList.DataContext = e.Result.Results;
				this.Focus();
			}
		}

		private void SearchBox_KeyUp(object sender, KeyEventArgs e)
		{
			if (String.IsNullOrEmpty(SearchBox.Text) == false && e.Key == Key.Enter)
			{
				// Start a progress bar animation
				SystemTray.SetProgressIndicator(this, new ProgressIndicator()
				{
					IsIndeterminate = true,
					IsVisible = true,
					Text = "Searching for address..."
				});

				// Create the search request
				GeocodeRequest geocodeRequest = new GeocodeRequest()
				{
					Credentials = new Credentials()
					{
						ApplicationId = Strings.BingMapsCredentials
					},
					Query = SearchBox.Text,
					Options = new GeocodeOptions()
					{
						Filters = new List<FilterBase>()
		                {
		                    new ConfidenceFilter()
		                    {
		                        MinimumConfidence = BingMapsGeocodeService.Confidence.High
		                    },
		                }
					}
				};

				// Execute the search
				this._geocodeServiceClient.GeocodeAsync(geocodeRequest);
			}
		}

		private void SearchResult_Tap(object sender, System.Windows.Input.GestureEventArgs e)
		{
			GeocodeResult geocodeResult = ((TextBlock)sender).Tag as GeocodeResult;

			Common.SaveContact(this._saveContactTask, geocodeResult.DisplayName, geocodeResult.Locations[0].Longitude, geocodeResult.Locations[0].Latitude, geocodeResult.Address);
		}

		private void SaveContactTask_Completed(object sender, SaveContactResult e)
		{
			// Check if the user tapped the save button
			if (e.TaskResult == TaskResult.OK)
			{
				MessageBox.Show("You may need to refresh contacts via Bluetooth on the Pioneer navigation system.", "Contact saved as POI", MessageBoxButton.OK);
				NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
			}
		}
	}
}